package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddresssBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddresssBookService addresssBookService;

    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook)
    {
        addressBook.setUserId(BaseContext.getCurrentId());
        addresssBookService.save(addressBook);


        return R.success(addressBook);
    }

    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook)
    {
        LambdaUpdateWrapper<AddressBook> luw=new LambdaUpdateWrapper<>();
        luw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        luw.set(AddressBook::getIsDefault,0);

        addresssBookService.update(luw);

        addressBook.setIsDefault(1);

        addresssBookService.updateById(addressBook);


        return R.success(addressBook);
    }
    @GetMapping("/{id}")
    public R<AddressBook>  get(@PathVariable Long id)
    {
        AddressBook addressBook = addresssBookService.getById(id);

        if (addressBook!=null)
            return R.success(addressBook);
        else
            return R.error("未查询到该对象");

    }




    @GetMapping("/default")
    public R<AddressBook> getDefault()
    {
        LambdaQueryWrapper<AddressBook> lqw=new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.eq(AddressBook::getIsDefault,1);

        AddressBook addressBook = addresssBookService.getOne(lqw);

        if (addressBook!=null)
        {
        return R.success(addressBook);
        }
        else {
            return R.error("没有找到该对象");
        }
    }


    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook)
    {
        addressBook.setUserId(BaseContext.getCurrentId());

        LambdaQueryWrapper<AddressBook> lqw=new LambdaQueryWrapper<>();
        lqw.eq(addressBook.getUserId()!=null,AddressBook::getUserId,addressBook.getUserId());
        lqw.orderByDesc(AddressBook::getUpdateTime);

        List<AddressBook> list = addresssBookService.list(lqw);
        return R.success(list);
    }


    @PutMapping
    public R<AddressBook> update(@RequestBody AddressBook addressBook)
    {
        addresssBookService.updateById(addressBook);

        return R.success(addressBook);
    }

    @DeleteMapping
    public R<String> delete(Long ids)
    {
        addresssBookService.removeById(ids);

        return R.success("删除成功");
    }

}
